package com.cskaoyan.wx.service;

import com.cskaoyan.bean.reverseengineering.MarketAddress;
import com.cskaoyan.bean.reverseengineering.MarketAddressExample;
import com.cskaoyan.bean.reverseengineering.MarketRegion;
import com.cskaoyan.bean.reverseengineering.MarketRegionExample;
import com.cskaoyan.mapper.MarketAddressMapper;
import com.cskaoyan.mapper.MarketRegionMapper;
import com.cskaoyan.mapper.MarketUserMapper;
import com.cskaoyan.wx.bean.bo.address.AddressSaveBO;
import com.cskaoyan.wx.bean.vo.address.AddressQueryDetailVO;
import com.cskaoyan.wx.bean.vo.address.AddressQueryVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 
 * @since 2022/05/08 14:59
 * @author tangwei
 */
@Service
public class WxAddressServiceImpl implements WxAddressService {

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketUserMapper marketUserMapper;

    @Autowired
    MarketRegionMapper marketRegionMapper;

    @Override
    public AddressQueryVO queryAddress(String username) {

        Integer page = 1;
        Integer limit = 15;
        String sort = "id";
        String order = "asc";

        PageHelper.startPage(page, limit);

        Integer userId = marketUserMapper.selectByusername(username);

        MarketAddressExample marketAddressExample = new MarketAddressExample();
        MarketAddressExample.Criteria criteria = marketAddressExample.createCriteria();
        marketAddressExample.setOrderByClause(sort + " " + order);

        // if (!(userId == null)) {
        //     criteria.andIdEqualTo(userId);
        // }
        criteria.andUserIdEqualTo(userId);

        criteria.andDeletedEqualTo(false);
        List<MarketAddress> marketAddresses = marketAddressMapper.selectByExample(marketAddressExample);

        ArrayList<AddressQueryDetailVO> addressQueryDetailVOS = new ArrayList<>();

        for (int i = 0; i < marketAddresses.size(); i++) {
            MarketAddress OneMarkAddress = marketAddresses.get(i);
            AddressQueryDetailVO addressQueryDetailVO = new AddressQueryDetailVO(OneMarkAddress.getAddTime(),
                    OneMarkAddress.getAddressDetail(), OneMarkAddress.getAreaCode(), OneMarkAddress.getCity(),
                    OneMarkAddress.getCounty(), OneMarkAddress.getDeleted(), OneMarkAddress.getId(), OneMarkAddress.getIsDefault(),
                    OneMarkAddress.getName(), OneMarkAddress.getProvince(), OneMarkAddress.getTel(), OneMarkAddress.getUpdateTime(),
                    OneMarkAddress.getUserId());

            addressQueryDetailVOS.add(addressQueryDetailVO);
        }

        PageInfo<MarketAddress> pageInfo = new PageInfo<>(marketAddresses);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();

        return new AddressQueryVO(total, pages, limit, page, addressQueryDetailVOS);

    }

    @Override
    public AddressQueryDetailVO showAddressDetail(Integer id) {
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(id);

        AddressQueryDetailVO addressQueryDetailVO = new AddressQueryDetailVO(marketAddress.getAddTime(),
                marketAddress.getAddressDetail(), marketAddress.getAreaCode(), marketAddress.getCity(),
                marketAddress.getCounty(), marketAddress.getDeleted(), marketAddress.getId(), marketAddress.getIsDefault(),
                marketAddress.getName(), marketAddress.getProvince(), marketAddress.getTel(), marketAddress.getUpdateTime(),
                marketAddress.getUserId());

        return addressQueryDetailVO;
    }

    @Override
    public void saveAddress(AddressSaveBO addressSaveBO) {
        Integer userId = marketUserMapper.selectByusername(addressSaveBO.getUsername());


        MarketAddress marketAddress = new MarketAddress();
        marketAddress.setUpdateTime(new Date());

        marketAddress.setAddressDetail(addressSaveBO.getAddressDetail());
        marketAddress.setAreaCode(addressSaveBO.getAreaCode());
        marketAddress.setCity(addressSaveBO.getCity());
        marketAddress.setCounty(addressSaveBO.getCounty());
        marketAddress.setId(addressSaveBO.getId());
        marketAddress.setIsDefault(addressSaveBO.getIsDefault());
        marketAddress.setName(addressSaveBO.getName());
        marketAddress.setProvince(addressSaveBO.getProvince());
        marketAddress.setTel(addressSaveBO.getTel());

        // 由用户名得到用户id,应该要求用户名不能重名？
        // MarketUserExample marketUserExample = new MarketUserExample();
        // MarketUserExample.Criteria criteria1 = marketUserExample.createCriteria();
        // if(!(addressSaveBO.getName() == null)) {
        //     criteria1.andUsernameEqualTo(addressSaveBO.getName());
        // }
        // List<MarketUser> marketUsers = marketUserMapper.selectByExample(marketUserExample);
        // marketAddress.setUserId(marketUsers.get(0).getId());
        //错了，这里的name是收货人的name，不是用户的，用户id怎么查？

        marketAddress.setUserId(userId);

        // 邮编哪里来的？
        // marketAddress.setPostalCode("0");
        MarketRegionExample marketRegionExample = new MarketRegionExample();
        MarketRegionExample.Criteria criteria2 = marketRegionExample.createCriteria();
        criteria2.andNameEqualTo(addressSaveBO.getCounty());
        List<MarketRegion> marketRegions = marketRegionMapper.selectByExample(marketRegionExample);
        marketAddress.setPostalCode(Integer.toString(marketRegions.get(0).getCode()));

        // 判断如果收货地址id在数据库了，就更新地址，否则新建地址
        MarketAddressExample marketAddressExample = new MarketAddressExample();
        MarketAddressExample.Criteria criteria = marketAddressExample.createCriteria();
        if (!(addressSaveBO.getId() == null)) {
            criteria.andIdEqualTo(addressSaveBO.getId());
        }

        List<MarketAddress> marketAddresses = marketAddressMapper.selectByExample(marketAddressExample);
        if (!(marketAddresses.size() == 0)) {
            // 更新收货地址

            // 得把除这个收货地址的其他地址的默认值设为相反数，当其他地址的默认值为0（非默认地址）
            // 要修改为的默认值，       现在这个的默认值
            Boolean othersIsDefault = !marketAddress.getIsDefault();
            if (othersIsDefault == false) {
                MarketAddress marketAddress1 = new MarketAddress();
                marketAddress1.setIsDefault(othersIsDefault);
                MarketAddressExample marketAddressExample1 = new MarketAddressExample();
                MarketAddressExample.Criteria criteria1 = marketAddressExample1.createCriteria();
                if (!(othersIsDefault == null)) {
                    criteria1.andIsDefaultEqualTo(marketAddress.getIsDefault());
                }
                marketAddressMapper.updateByExampleSelective(marketAddress1, marketAddressExample1);
            }

            marketAddressMapper.updateByPrimaryKeySelective(marketAddress);
        } else {
            // 新建收货地址

            // 得把除这个收货地址的其他地址的默认值设为相反数，当其他地址的默认值为0（非默认地址）
            // 要修改为的默认值，       现在这个的默认值
            Boolean othersIsDefault = !marketAddress.getIsDefault();
            if (othersIsDefault == false) {
                MarketAddress marketAddress1 = new MarketAddress();
                marketAddress1.setIsDefault(othersIsDefault);
                MarketAddressExample marketAddressExample1 = new MarketAddressExample();
                MarketAddressExample.Criteria criteria1 = marketAddressExample1.createCriteria();
                if (!(othersIsDefault == null)) {
                    criteria1.andIsDefaultEqualTo(marketAddress.getIsDefault());
                }
                marketAddressMapper.updateByExampleSelective(marketAddress1, marketAddressExample1);
            }

            marketAddress.setAddTime(new Date());
            marketAddress.setDeleted(false);
            marketAddressMapper.insertSelective(marketAddress);

        }
    }

    @Override
    public void deleteAddress(Map deleteAddress) {
        Integer deleteAddressId = (Integer) deleteAddress.get("id");

        MarketAddress marketAddress = new MarketAddress();
        marketAddress.setId(deleteAddressId);

        marketAddress.setDeleted(true);

        marketAddress.setUpdateTime(new Date());

        marketAddressMapper.updateByPrimaryKeySelective(marketAddress);
    }
}